#-*- coding: utf-8 -*_

import logging

class LevelFileHandler(logging.FileHandler):
    
    def __init__(self, level=logging.INFO, **kwargs):
	self.level = level
	logging.FileHandler.__init__(self, **kwargs)
	self.setLevel(level)
    
    def emit(self, record):
	if record.levelno == self.level:
	    logging.FileHandler.emit(self, record)


class ErrorLogHandler(logging.FileHandler):
    
    def __init__(self, level=logging.WARNING, **kwargs):
	logging.FileHandler.__init__(self, **kwargs)
	self.setLevel(level)
	formatter = logging.Formatter("[%(levelname)s] %(message)s")
	self.setFormatter(formatter)
    
    def emit(self, record):
	if record.levelno != logging.INFO:
	    logging.FileHandler.emit(self, record)
	

# singleton 
class Logger:
    logger = None
    def __init__(self, debug=False):
	if self.__class__.logger is None:
	    self.__class__.dbg = debug
	    self.__class__.logger = logging.getLogger('logger')
	    self.__class__.logger.setLevel(logging.DEBUG and debug or logging.INFO)
	
	    console = logging.StreamHandler()
	    console.setLevel(logging.DEBUG and debug or logging.WARNING)

	    formatter = logging.Formatter("[%(levelname)s] %(message)s")
	    console.setFormatter(formatter)
	    self.__class__.logger.addHandler(console)

    def initFile(self, filename, mode="w"):
	logfile = ErrorLogHandler(logging.DEBUG and self.__class__.dbg or logging.WARNING, filename=filename, mode=mode)
	self.__class__.logger.addHandler(logfile)

    def initDataFile(self, filename, mode='w'):
	output = LevelFileHandler(logging.INFO, filename=filename, mode=mode)
	self.__class__.logger.addHandler(output)

    def debug(self, msg, *args, **kwargs):
	self.__class__.logger.debug(msg, *args, **kwargs)
    
    def info(self, msg, *args, **kwargs):
	self.__class__.logger.info(msg, *args, **kwargs)
    
    def warning(self, msg, *args, **kwargs):
	self.__class__.logger.warning(msg, *args, **kwargs)
    
    def error(self, msg, *args, **kwargs):
	self.__class__.logger.error(msg, *args, **kwargs)

    def critical(self, msg, *args, **kwargs):
	self.__class__.logger.critical(msg, *args, **kwargs)

